﻿//void testLog(){
//	Logger logger("log.txt");
//	logger.log(LogLevel::INFO, "Starting to test...");
//	int id = 42;
//	std::string action = "login";
//	double duration = 3.5;
//	std::string world = "world";
//
//	logger.log(LogLevel::INFO, "User {} performed {} in {} seconds", id, action, duration);
//	logger.log(LogLevel::INFO, "Hello {}", world);
//	logger.log(LogLevel::INFO, "this is a test messageeeeeeeeeeeeeeeee");
//	logger.log(LogLevel::INFO, "Multiple placeholders : {}, {}, {}", 1, 2, 3);
//}

#include <csignal>
#include <thread>
#include <mutex>
#include "AsioIOServicePool.h"
#include "CServer.h"
#include "ConfigMgr.h"
#include <boost/filesystem.hpp>
#include <iostream>
#include "Logger.h"
#include "RedisMgr.h"
#include "FileTransferServiceImpl.h"

int main()
{
	auto& cfg = ConfigMgr::Inst();
	auto server_name = cfg["SelfServer"]["Name"];

	try {
		//将登录数设置为0
		RedisMgr::GetInstance()->HSet(LOGIN_COUNT, server_name, "0");

		//定义一个GrpcServer
		std::string server_address(cfg["SelfServer"]["Host"] + ":" + cfg["SelfServer"]["RPCPort"]);
		FileTransferServiceImpl service;
		grpc::ServerBuilder builder;
		// 监听端口和添加服务
		builder.AddListeningPort(server_address, grpc::InsecureServerCredentials());
		builder.RegisterService(&service);
		// 构建并启动gRPC服务器
		std::unique_ptr<grpc::Server> server(builder.BuildAndStart());
		std::cout << "FileTransferRPC Server listening on " << server_address << std::endl;
		//单独启动一个线程处理grpc服务
		std::thread  grpc_server_thread([&server]() {
			server->Wait();
			});


		// 读取线程池配置
		size_t tcp_threads = atoi(cfg["SelfServer"]["TcpThreads"].c_str());
		auto pool = AsioIOServicePool::GetInstance();
		pool->Init(tcp_threads);

		// 创建独立的信号处理上下文 
		boost::asio::io_context signal_io;
		boost::asio::signal_set signals(signal_io, SIGINT, SIGTERM);
		 //信号处理逻辑（需捕获池对象）
		signals.async_wait([&signal_io, pool](auto, auto) {
			signal_io.stop();         // 停止信号处理循环 
			pool->Stop();            // 停止双池（关键修改点2）
			});

		// TCP 服务实例 
		auto tcp_port_str = cfg["SelfServer"]["TcpPort"];
		CServer tcp_server(pool->GetIOService(),
			/*std::atoi(tcp_port_str.c_str())*/8090);

		// 运行信号处理的IO上下文
		signal_io.run();
	}
	catch (std::exception& e) {
		std::cerr << "Exception: " << e.what() << endl;
	}
	return 0;
}
